from woniuatm_2.utility import *
from woniuatm_2.user import *
import time

history_path = os.path.abspath('..') + '\\data\\userrecord.txt'

# 查询
def query():
    from woniuatm_2.user import login_index
    with open(userinfo_path) as file:
        user_list = file.readlines()

    print(user_list[login_index])
    from woniuatm_2.menu import main_menu
    main_menu()


# 存款
def deposite():
    money = input("请输入你要存的钱：")
    if check_number(money):
        from woniuatm_2.user import login_index
        change_balance(login_index, int(money))
        from woniuatm_2.menu import main_menu
        main_menu()
    else:
        print("请输入正确的金额.")
        deposite()

# 取款
def withdraw():
    money = input("请输入你要存的钱：")
    if check_number(money):
        from woniuatm_2.user import login_index
        change_balance(login_index, int(money)*-1)
        from woniuatm_2.menu import main_menu
        main_menu()
    else:
        print("请输入正确的金额.")
        deposite()


# 转账
def transer():
    username = input("请输入对方账户：")
    money = input("请输入转账金额：")
    to_index = check_user(username)
    if to_index == -1:
        print("对方账户名不存在，请重新输入.")
        transer()
    else:
        if check_number(money):
            change_balance(login_index, int(money) * -1)
            change_balance(to_index, int(money))
            from woniuatm_2.menu import main_menu
            main_menu()
        else:
            print("请输入正确的金额.")


# 流水
def history():
    from woniuatm_2.user import login_index
    with open(userinfo_path) as file:
        user_list = file.readlines()
    username = user_list[login_index].split(',')[0]

    with open(history_path, encoding='utf-8') as file:
        history_list = file.readlines()

    for history in history_list:
        if history.startswith(username):
            print(history, end='')

    from woniuatm_2.menu import main_menu
    main_menu()


# 直接向userinfo.txt文件中修改余额，并写回
def change_balance(user_index, money):
    user_list = read_user()
    temp_list = user_list[user_index].split(',')
    username = temp_list[0]
    password = temp_list[1]
    balance = temp_list[2]
    phone = temp_list[3]

    balance = str(int(balance) + int(money))
    user_list[user_index] = username + ',' + password + ',' + balance + ',' + phone

    user_file = open(userinfo_path, mode='w')
    user_file.writelines(user_list)
    user_file.close()

    # 写入历史流水信息
    update_time = time.strftime('%Y-%m-%d %H:%M:%S')
    if money > 0:
        history = f"{username},{update_time},存款[{money}]元.\n"
    else:
        history = f"{username},{update_time},取款[{-money}]元.\n"

    with open(history_path, mode='a+', encoding='utf-8') as file:
        file.write(history)